import request from '@/utils/request'
import { createSlice } from '@reduxjs/toolkit'
import { setToken, getToken } from '@/utils/auth'
export const login = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'login',
  // 1. 定义变量(状态数据)
  initialState: {
    // 
    token: getToken() || ''
  },
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    changeToken (state, action) {
      state.token = action.payload
    },
    delTokenRd (state) {
      state.token = ''
    }
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { changeToken, delTokenRd } = login.actions

// 3. 异步action
export const loginAction = (payload) => {

  return async (dispatch, getState) => {
    console.log(payload)
    const { data } = await request.post('/authorizations', payload)
    console.log('data')
    // dispatch(add())
    console.log(data)
    dispatch(changeToken(data.data.token))
    setToken(data.token)
    // localStorage.setItem('geek-token', data.token)
  }
}

// 导出reducer(创建store使用)
export default login.reducer